#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2016年6月9日


@author: xiezc
'''
import pymysql
import datetime
import os.path
import shutil
import random

def add_song2db(songs):
        """添加一批歌曲到数据库中
           songs是传进来的包含歌曲的list
           list中的一个元素是包含歌曲信息的dict
        """
        now = datetime.datetime.now()
        parms = [] 
        for song in songs:
            x = ('kg'+now.strftime("%H%M%S")+str(random.randrange(1000)), song["author"], song["sname"], '', '', '', song["songLink"], now.strftime("%Y-%m-%d %H:%M:%S"),'1','500')
            parms.append(x)
        try:
            # 获取一个数据库连接，注意如果是UTF-8类型的，需要制定数据库
            conn = pymysql.connect('localhost', 'root', 'rootxzc', 'mytest', 3306, charset='utf8')
            cur = conn.cursor()  # 获取一个游标
            cur.executemany("insert into hotsong(sid,author,sname,artistId,artistName,lrcLink,songLink,createTime,hotNum,other) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", parms)
            conn.commit()
            print('向数据库中添加了%d首新歌曲' % len(parms))
        finally:
            cur.close()
            conn.close()
            
def get_song_set():
        '''一次获得所有歌曲的sid并放入set中，以此来判断歌曲数据库中是否已经存在从而决定是否下载'''
        sidset = set()
        try:  
            # 获取一个数据库连接，注意如果是UTF-8类型的，需要制定数据库
            conn = pymysql.connect('localhost', 'root', 'rootxzc', 'mytest', 3306, charset='utf8')
            cur = conn.cursor()  # 获取一个游标
            cur.execute('select songLink from hotsong')
            data = cur.fetchall()
            for d in data:
                sidset.add(d[0].strip())
        except Exception as e:
            print("get_song发生异常" + e)
        finally:
            cur.close()  # 关闭游标
            conn.close()  # 释放数据库资源
        print("获得数据库的所有歌曲id的set集合，set大小为：%d" % len(sidset))
        return sidset
    
    

def main():
    path='F:\KuGou'
    pathDir =  os.listdir(path)
    songs=[]
    set= get_song_set()
    for allDir in pathDir:
        child = os.path.join(path, allDir)
        dst='E:/javaWorkSpace/wechat/target/wechat/WEB-INF/music/myMusic/' + allDir
        if os.path.isdir(child):
            continue
        songLink =  'myMusic/'+allDir.strip()
        if songLink in set:
            print(allDir+"-----------------")
            continue
        with open(child, 'rb') as fsrc:
                with open(dst, 'wb') as fdst:
                    while 1:
                        buf = fsrc.read()
                        if not buf:
                            break
                        fdst.write(buf)
                    if allDir.index('-')<0:
                        author=''
                        sname=allDir.strip().split('.')[0]
                        songs.append({'author':author,"sname":sname})
                    else:
                        sMsg =  allDir.split('-')
                        author=sMsg[0].strip()
                        sname=sMsg[1].strip().split('.')[0]
                        songs.append({'author':author,"sname":sname,'songLink':songLink})
        print(child)  
                                    
    add_song2db(songs)

if __name__ == "__main__":
    main()
    
     